package com.ititer.web.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Simply process static files for RESTful URL in development environment.
 * When deploy to on-site system, this work can deliver to Apache or other front end web server.
 * @author aceyin
 *
 */
public class StaticResourceFilter implements Filter {
	final Logger logger = LoggerFactory.getLogger(StaticResourceFilter.class);

	private static final List<String> staticResources = new ArrayList<String>();
	private static final String fileTypes = ".jpg,.gif,.png,.jpeg,.css,.js,.html,.htm,.xml,.json,.txt";

	public void init(FilterConfig filterConfig) throws ServletException {
		staticResources.addAll(Arrays.asList(fileTypes.split(",")));
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String requestURI = req.getRequestURI();
		logger.debug("Incoming request URI is : {} ", requestURI);
		if (StringUtils.isBlank(requestURI)) {
			requestURI = "/";
		}
		if (requestURI.indexOf(".") == -1) {
			logger.debug("Request URI not contains '.' continue chain.");
			chain.doFilter(request, response);
		} else {
			String filetype = requestURI.substring(requestURI.lastIndexOf("."), requestURI.length());
			logger.debug("Request file type is {} ", filetype);
			if (fileTypes.contains(filetype)) {
				logger.debug("Request URI {} is a static resource, forward it to the static resource.", requestURI);
				req.getRequestDispatcher(requestURI).forward(req, res);
			} else {
				logger.debug("Request URI {} is not a static resource, continue chain", requestURI);
				chain.doFilter(request, response);
			}
		}
	}

	public void destroy() {
	}

}
